package com.hxh.bank.branch.spider;

import com.hxh.bank.branch.vo.BankBranchVO;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @author huangxunhui
 * Date: Created in 2021/5/16 16:52
 * Utils: IntelliJ IDEA
 * Description: Json.cn 爬虫
 */
@Slf4j
public class JsonCnSpider extends BankBranchSpider {

    /**
     * 爬取URL
     */
    private static final String URL = "http://www.jsons.cn/banknum/";


    @Override
    protected BankBranchVO parse(String bankBranchCode) {

        try {
            log.info("json.cn-支行信息查询：{}", bankBranchCode);

            // 设置请求参数
            Map<String, String> map = new HashMap<>(2);
            map.put("keyword", bankBranchCode);
            map.put("txtflag", "1");

            // 查询支行信息
            Document doc = Jsoup.connect(URL).data(map).post();


            Elements td = doc.selectFirst("tbody")
                    .selectFirst("tr")
                    .select("td");

            if (td.size() < 3) {
                return null;
            }

            // 获取详情url
            String detailUrl = td.get(3)
                    .selectFirst("a")
                    .attr("href");

            if (StringUtil.isBlank(detailUrl)) {
                return null;
            }

            log.info("json.cn-支行详情-联行号:{}, 详情页:{}", bankBranchCode, detailUrl);

            // 获取详细信息
            Elements footers = Jsoup.connect(detailUrl).get().select("blockquote").select("footer");

            String bankName = footers.get(1).childNode(2).toString();
            String bankCode = footers.get(2).childNode(2).toString();
            String provName = footers.get(3).childNode(2).toString();
            String cityName = footers.get(4).childNode(2).toString();

            return BankBranchVO.builder()
                    .bankName(bankName)
                    .bankCode(bankCode)
                    .provName(provName)
                    .cityName(cityName)
                    .build();

        } catch (IOException e) {
            log.error("json.cn-支行信息查询失败:{}, 失败原因:{}", bankBranchCode, e.getLocalizedMessage());
            return null;
        }
    }

    @Override
    protected boolean useNextSpider(BankBranchVO vo) {
        return vo == null;
    }

}
